<template>
    <div>
        <!-- <div class="cinemaBack" @click="goBack">
            <div><van-icon name="arrow-left" color="#333" size="18" /></div>
            <div class="cinemaName"> {{ showData.cinema_name }}</div>
        </div> -->
        <div class="head">
            <img class="head-back-img" @click="goBack" src="../assets/back.svg" alt="">
            <div class="title">{{ showData.cinema_name }}</div>
        </div>
        <van-overlay :show="loading" class="full-page-loading">
            <div class="loading-content">
                <div class="loading-box">
                    <van-loading color="#fff" size="24px" vertical>{{ titles }}...</van-loading>
                </div>
            </div>
        </van-overlay>
        <seat-map ref="seatMap" :max_can_buy="filmData.max_can_buy" :max_column="filmData.max_column"
            :max_row="filmData.max_row" :seat_list="seatData" :area_data="areaData" :showName="showData.hall_name"
            :selected-seats="selectedSeats" @update-selected="handleSeatChange" :selectedImage="filmData.pic" />
        <div class="footers">
            <div class="selectPrsonInfo">
                <div class="tops">
                    <div class="film_name">{{ showData.film_name }}</div>
                    <div class="change_count" @click="toggleSessionList">
                        <span>{{ isSessionListVisible ? '收起场次' : '切换场次' }}</span>
                        <van-icon size="16" :name="isSessionListVisible ? 'arrow-up' : 'arrow-down'" color="#EE473B" />
                    </div>
                </div>
                <div class="selectTime">
                    {{ formatShowTime(showData) }} {{ showData.version_type }}
                </div>
                <div class="batch" v-if="isSessionListVisible">
                    <div v-for="(item, index) in sessionList" :key="index" class="sessonStyle"
                        :class="{ 'selected': selectedSessionIndex === index }" @click="selectSession(index, item)">
                        <div>{{ getTimes(item.show_time) }}</div>
                        <div style="color: #999;">{{ item.version_type }}</div>
                        <div>{{ item.net_price }}起</div>
                    </div>
                </div>

                <van-divider :margin="3" />
                <div class="hasSelect">
                    <div class="hasSelectSeats" v-for="(item, index) in seatesPrice" :key="index"
                        @click="removeSeat(index)">
                        <div class="seat_names">
                            <div>{{ item.seat_name }}</div>
                            <div> {{ item.price }}</div>
                        </div>
                        <div class="line"></div>
                        <div><van-icon name="cross" color="#999" size="16" /></div>
                    </div>
                </div>
            </div>
            <div class="submitButton" :class="{ 'disabled': !hasSelectedSeats }" @click="handleSubmit">
                {{ submitButtonText }}
            </div>
        </div>
    </div>
</template>

<script>
import plantAPI from "@/api/plant";
import SeatMap from '../components/SeatMap.vue';
import { Toast } from 'vant';
export default {
    components: {
        SeatMap
    },
    data() {
        return {
            titles: '正在加载中',
            areaData: "",
            // 选中座位
            seatesPrice: [],
            // 选中场次索引
            selectedSessionIndex: -1,
            // 场次数据
            sessionList: [],
            // 控制场次列表显示状态
            isSessionListVisible: false,
            loading: true,
            filmData: {},
            showData: {},
            seatData: [],
            selectedSeats: [],
            sortedAreaData: [],
            autoSelectedSeats: []
        }
    },
    computed: {
        hasSelectedSeats() {
            return this.selectedSeats.length > 0;
        },
        totalPrice() {
            let total = 0;
            this.seatesPrice = []
            const allSelectedSeats = [...this.selectedSeats];
            allSelectedSeats.forEach(seatName => {
                const seat = this.seatData.find(s => s.seat_name == seatName);
                if (seat) {
                    this.seatesPrice.push(seat)
                    total += Number(seat.price);
                }
            });
            return total.toFixed(2);
        },
        submitButtonText() {
            if (!this.hasSelectedSeats) {
                return "请先选择座位";
            } else {
                return `${this.totalPrice} 确认选座`;
            }
        }
    },
    created() {
        // 排期id  
        this.getSeatList(this.$route.query.show_id)
    },
    methods: {
        goBack() {
            this.$router.go(-1);
        },
        formatShowTime(showData) {
            if (!showData || !showData.show_date || !showData.show_time || !showData.close_time) {
                return '';
            }
            // 解析日期
            const showDate = new Date(showData.show_date);
            const showTime = new Date(showData.show_time);
            const closeTime = new Date(showData.close_time);
            // 获取今天的日期
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            // 计算日期差
            const diffDays = Math.floor((showDate - today) / (1000 * 60 * 60 * 24));
            // 确定日期显示文本
            let dateText = '';
            if (diffDays === 0) {
                dateText = '今天';
            } else if (diffDays === 1) {
                dateText = '明天';
            } else if (diffDays === 2) {
                dateText = '后天';
            } else {
                const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                dateText = weekDays[showDate.getDay()];
            }
            // 获取月份和日期
            const month = showDate.getMonth() + 1;
            const day = showDate.getDate();
            // 获取小时和分钟
            const startHours = showTime.getHours().toString().padStart(2, '0');
            const startMinutes = showTime.getMinutes().toString().padStart(2, '0');
            const endHours = closeTime.getHours().toString().padStart(2, '0');
            const endMinutes = closeTime.getMinutes().toString().padStart(2, '0');

            return `${dateText} ${month}月${day}日 ${startHours}:${startMinutes}-${endHours}:${endMinutes}`;
        },
        getSeatList(showId) {
            // 座位
            plantAPI.getseatAPI({
                showId
            }).then(res => {
                // let data = JSON.parse(res.data.body).data.show.area_price.split(";")
                this.filmData = JSON.parse(res.data.body).data.film
                this.showData = JSON.parse(res.data.body).data.show
                this.seatData = JSON.parse(res.data.body).data.seat_list
                let areaData = JSON.parse(res.data.body).data.show.area_price
                this.areaData = areaData
                // 区域价格
                if (!areaData) return;
                const areas = areaData.split(';').map(item => {
                    const parts = item.trim().split(',');
                    const areaPart = parts[0].split(':');
                    const pricePart = parts[1].split(':');
                    return {
                        area_id: areaPart[1],
                        price: parseFloat(pricePart[1]),
                        settle_price: parts[2] ? parseFloat(parts[2].split(':')[1]) : 0
                    };
                });
                areas.sort((a, b) => a.price - b.price);
                this.sortedAreaData = areas
            }).finally(() => {
                this.loading = false
            })
        },
        // 添加删除座位的方法
        removeSeat(index) {
            const removedSeat = this.seatesPrice.splice(index, 1)[0];
            const seatIndex = this.selectedSeats.indexOf(removedSeat.seat_name);
            if (seatIndex !== -1) {
                this.selectedSeats.splice(seatIndex, 1);
            }
        },
        // 切换场次列表显示状态
        toggleSessionList() {
            this.isSessionListVisible = !this.isSessionListVisible;
            // 如果显示场次列表且当前没有数据，则加载数据
            if (this.isSessionListVisible && this.sessionList.length === 0) {
                this.loadSessionData();
            }
        },
        // 加载场次数据
        loadSessionData() {
            let data = [];
            plantAPI.getshowAPI(this.$route.query.cinema_id).then(res => {
                JSON.parse(res.data.body).data.forEach(element => {
                    if (element.film_id == this.showData.film_id && element.show_date == this.showData.show_date) {
                        data.push(element)
                    }
                });
                this.sessionList = data;
                // 如果有数据，默认选中第一个场次
                if (this.sessionList.length > 0) {
                    this.selectedSessionIndex = 0;
                }
            });
        },
        // 处理场次选择
        selectSession(index, item) {
            this.selectedSessionIndex = index;
            // 这里可以添加其他逻辑，比如根据选择的场次更新座位信息
            this.loading = true
            this.getSeatList(item.show_id)
        },
        getTimes(fullTime) {
            const timePart = fullTime.split(' ')[1]; // 得到 "19:15:00"
            const shortTime = timePart.substring(0, 5); // 截取前5个字符 "19:15"
            return shortTime;
        },
        handleSeatChange(selectedSeats) {
            if (selectedSeats.length == 0) {
                this.seatesPrice = []
            }

            this.selectedSeats = selectedSeats;
        },
        handleSubmit() {
            if (!this.hasSelectedSeats) {
                this.$toast('请先选择座位');
                return;
            }
            // 提交选座信息
            let allseat_id = ""
            let allseat_name = ""
            this.selectedSeats.forEach(item => {
                this.seatData.forEach(items => {
                    if (item == items.seat_name) {
                        allseat_id += items.seat_id + ','
                        allseat_name += items.seat_name + ','
                    }
                })
            })

            allseat_id = allseat_id.slice(0, -1);
            allseat_name = allseat_name.slice(0, -1)

            // Toast('正在锁座中');
            this.titles = '正在锁座中'
            this.loading = true
            plantAPI.getlockAPI({
                phone: localStorage.getItem("phonenumber"),
                seatIds: allseat_id,
                seatNames: allseat_name,
                showId: this.$route.query.show_id
            }).then(res => {
                if (JSON.parse(res.data.body).code != 200) {
                    Toast(JSON.parse(res.data.body).msg);
                    this.loading = false
                    return;
                } else {
                    sessionStorage.setItem(
                        'payData',
                        JSON.stringify({
                            showData: this.showData,
                            filmData: this.filmData,
                            seatesPrice: this.seatesPrice,
                            totalPrice: this.totalPrice,
                            settle_amount: JSON.parse(res.data.body).data.settle_amount,
                            order_no: JSON.parse(res.data.body).data.order_no
                        })
                    );

                    // 2. 只携带极短的 order_no 做跳转
                    window.location.replace(
                        `https://xhjzh.life/wx/?order_no=${encodeURIComponent(
                            JSON.parse(res.data.body).data.order_no
                        )}`
                    );
                    this.loading = false
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.hasSelect {
    display: flex;
    align-items: center;
    margin-left: 6px;
    overflow-x: auto;
    /* 添加横向滚动 */
    white-space: nowrap;
    /* 防止子元素换行 */
    padding-bottom: 10px;
    /* 为滚动条留出空间 */
    -webkit-overflow-scrolling: touch;
    /* iOS平滑滚动 */

    .hasSelectSeats {
        display: inline-flex;
        /* 改为行内flex布局 */
        align-items: center;
        padding: 0 10px;
        height: 46px;
        background: #F6F6F6;
        border-radius: 6px;
        margin-right: 8px;
        /* 添加右边距 */
        flex-shrink: 0;
        /* 防止元素被压缩 */
        cursor: pointer;
        /* 添加指针样式 */
    }

    .line {
        width: 0px;
        height: 32px;
        border: 0.5px solid #D1D1D1;
        margin: 0 5px;
    }

    .seat_names {
        text-align: center;
        padding-right: 10px;

        >div:first-child {
            height: 18px;
            font-family: PingFang SC;
            font-weight: 500;
            font-size: 13px;
            color: #1A1A1A;
        }

        >div:last-child {
            height: 17px;
            font-family: PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #1A1A1A;
        }
    }
}

.batch {
    display: flex;
    align-items: center;
    margin-top: 10px;
    overflow-x: auto;
    /* 添加横向滚动 */
    white-space: nowrap;
    /* 防止子元素换行 */
    padding-bottom: 10px;
    /* 为滚动条留出空间 */
    -webkit-overflow-scrolling: touch;
    /* iOS平滑滚动 */

    .sessonStyle {
        display: inline-flex;
        /* 改为行内flex布局 */
        flex-direction: column;
        justify-content: center;
        text-align: center;
        width: 70px;
        height: 70px;
        background: #ebc6d03d;
        color: #666;
        font-size: 13px;
        margin: 0 8px;
        border-radius: 4px;
        border: 1px solid transparent;
        transition: all 0.3s;
        cursor: pointer;
        flex-shrink: 0;
        /* 防止元素被压缩 */

        >div {
            height: 23px;
            line-height: 23px;
        }

        &.selected {
            background: #ebc6d080;
            border: 1px solid #EE473B;
        }

        &:hover {
            background: #ebc6d060;
        }
    }
}

.van-divider {
    margin: 10px 0;
    padding: 0 12px;
}


.footers {
    width: 351px;
    margin: auto;
}

.submitButton {
    margin-top: 30px;
    width: 351px;
    height: 46px;
    line-height: 46px;
    background: linear-gradient(96deg, #F03E35 0%, #FD5267 100%);
    box-shadow: 0px 3px 6px rgba(238, 71, 59, 0.16);
    border-radius: 24px;
    font-family: PingFang SC;
    font-size: 14px;
    color: #FFFFFF;
    text-align: center;
    cursor: pointer;
}

.submitButton.disabled {
    background: linear-gradient(96deg, #F03E35 0%, #FD5267 100%);
    box-shadow: 0px 3px 6px rgba(238, 71, 59, 0.16);
    box-shadow: none;
    cursor: not-allowed;
}

.selectPrsonInfo {
    margin-top: 20px;
    padding: 16px 0 5px 0;
    width: 351px;
    background: #FFFFFF;
    box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.16);
    border-radius: 14px;
}

.tops {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 16px 8px;
}

.tops .film_name {
    height: 22px;
    font-family: PingFang SC;
    font-weight: 500;
    font-size: 16px;
    color: #1A1A1A;
}

.tops .change_count {
    display: flex;
    align-items: center;
    cursor: pointer;

    span {
        width: 56px;
        height: 20px;
        font-family: PingFang SC;
        font-size: 14px;
        color: #EE473B;
    }
}

.selectTime {
    font-family: PingFang SC;
    text-align: left;
    margin-left: 16px;
    font-size: 13px;
    color: #575757;
}

.cinemaBack {
    height: 64px;
    line-height: 64px;
    display: flex;
    align-items: center;
    /* 确保垂直居中 */
    margin-left: 12px;
}

.cinemaBack div {
    display: inline-flex;
    vertical-align: middle;
}

.cinemaBack .van-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 64px;
    line-height: 64px;
    /* 与容器同高 */
}

.cinemaName {
    font-family: PingFang SC;
    font-weight: 500;
    font-size: 16px;
    color: #1A1A1A;
    display: flex;
    align-items: center;
    height: 64px;
    line-height: 64px;
}

.full-page-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #F5F6F8;

    .loading-content {
        .loading-box {
            background-color: #000;
            padding: 10px 30px;
            border-radius: 8px;

            .van-loading {
                color: #fff;

                &__text {
                    margin-top: 10px;
                    color: #fff;
                    font-size: 16px;
                }
            }
        }
    }
}

.head {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    position: relative; // 关键：设置相对定位
    background-color: #ffffff;

    .head-back-img {
        width: 20px;
        height: 20px;
        position: absolute;
        left: 15px;
    }

    .title {
        width: 100%;
        text-align: center;
        font-size: 16px;
        color: #000000;
    }
}
</style>